import Vue from 'vue'
import Vuex from 'vuex'
import SystemApi from '@/api/SystemApi'
import router from '@/router'

Vue.use(Vuex)

const modulesFiles = require.context('./module', true, /\.js$/)
const modules = modulesFiles.keys().reduce((modules, modulePath) => {
  const moduleName = modulePath.replace(/^\.\/(.*)\.\w+$/, '$1')
  const value = modulesFiles(modulePath)
  modules[moduleName] = value.default
  return modules
}, {})

const store = new Vuex.Store({
  modules
})
setTimeout(() => {
  SystemApi.isAuthen().then(isAuthen => {
    if (isAuthen) {
      store.dispatch('loadInfo')
    } else {
      if (window.location.href.indexOf('/login') === -1) {
        router.replace('/login')
        location.reload()
      }
    }
  }).catch(err => {
    console.log(err)
  })
})

export default store
